import React from 'react';
import { Link } from 'react-router-dom';
import { observer, inject } from 'mobx-react';


import ImageLoader from '../../styles/ImageLoader'

import 'fabric';

import $ from 'zepto';

import { Icon, message, Button, Modal } from 'antd';

import { PageEventType } from '../../utils/PageEventType'

import './index.scss'

import WinHelper from '@src/utils/WinHelper'



@inject('showStore')
@inject('baseStore')
@observer
class ShowPage extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			show_free_dialog: true, //自由临摹层
			tenCmNeedZoom: 1,
			visible: true,
			side_show: true,
			moveCanvas: false,
			canvas_orign: {
				width: 1210,
				height: 610
			},
			show_img: false,
			show_img_url: '',
			show_video: false,
			show_video_url: '',
			bgImgList: [{
				Name: '米字格',
				Icon: 'mi_icon',
				ImgUrl: 'http://www.besteasylearn.com/pic/canvas_bg/米_1200x600.png',
				Width: 1200,
				Height: 600
			}, {
				Name: '田字格',
				Icon: 'tian_icon',
				ImgUrl: 'http://www.besteasylearn.com/pic/canvas_bg/田_1200x600.png',
				Width: 1200,
				Height: 600
			}],
			bgImgActivedIndex: 0,
			canvasMyMod: 0, // 左侧进入模式   0.展示模式  1.单点击编辑  2.拖放
			curRightActivedItem: null,  //右侧当前激活  用于单击编辑框

			freeBgUrl: 'http://www.besteasylearn.com/pic/canvas_bg/米_1200x600.png'
		};

		this._canvas = null;
		this.container = null;

	}

	renderImgArr = (arr, canvas) => {

		var toAddImg = [];

		arr.forEach((item, index) => {


			fabric.Image.fromURL(item.ImageURL, function (oImg) {

				oImg.width = item['ImgWidth'] || 300;
				oImg.height = item['ImgHeight'] || 300;

				oImg.top = (Math.floor(index / 4)) * 300;
				oImg.left = (index % 4) * 300;

				console.log(`${index}:${oImg.top}_${oImg.left}`);

				oImg.preserveObjectStacking = true;

				oImg.scaleX = oImg.width / 300;
				oImg.scaleY = oImg.height / 300;

				oImg.crossOrigin = 'anonymous';

				oImg.selectable = false;

				canvas.add(oImg);
				toAddImg.push(oImg);
			});
		})

		// var group = new fabric.Group(toAddImg, {
		// 	left: 0,
		// 	top: 0
		// });
		// canvas.add(group);

	}


	componentDidMount() {

		// 计算出如果调成安世高10cm的绽放比例
		var my_px = WinHelper.mmToPx(100);
		my_px = Math.round(my_px);
		console.log(my_px, "=======my_px=======");
		var tenCmNeedZoom = my_px / 300;
		this.setState({
			tenCmNeedZoom: tenCmNeedZoom
		})

		this.props.baseStore.topHeader.show = true;
		//因此页入口可能有多个 所以 backTo在来源页就设置好


		var directoryId = this.props.match.params.directoryId || '';
		if (directoryId.length == 0) {
			// alert("即查即练")
		} else {
			this.props.showStore.GetWordListById(directoryId);
		}

		var canvas = this._canvas;
		var moveCanvas = this.moveCanvas;

		this._canvas = new fabric.Canvas('canvas', {
			isDrawingMode: false,
			width: 1200,
			height: 600,
			selections: false
			// backgroundColor: '#D6F8FF'
		});
		this._canvas.selection = false;
		this._canvas.preserveObjectStacking = false;
		//this._canvas.setBackgroundImage('http://www.besteasylearn.com/pic/1210x610.png', this._canvas.renderAll.bind(this._canvas));


		var curBgImgObj = this.state.bgImgList[this.state.bgImgActivedIndex];
		$(this._canvas.wrapperEl).css({
			// backgroundImage: "url(http://www.besteasylearn.com/pic/1210x610.png)"
			backgroundImage: `url(${curBgImgObj.ImgUrl})`

		});

		var that = this;

		var start_pos = {
			x: 0,
			y: 0
		};

		var $canvas_container = $(".canvas-container");


		this.container = {
			width: 1920, //侧边
			height: 1080
		}

		var container = this.container;


		$(".canvas-container").css({
			left: container.width / 2 - this.getDomRealData($canvas_container).css_width / 2,
			top: container.height / 2 - this.getDomRealData($canvas_container).css_height / 2
		});

		var container_pos = {
			x: $('.canvas-container').position().left,
			y: $('.canvas-container').position().top
		}


		var that = this;

		document.querySelector(".canvas_can_drag").addEventListener('click', function () {


			var mask = `<div class="canvas_mask"></div>`;

			if ($('.canvas_mask').length == 0) {
				$(".canvas-container").append($(mask));
			} else {
				$('.canvas_mask').remove();
				return;
			}


			$('.canvas_mask').unbind().bind(PageEventType.moveEvent, function (evt) {

				if (moveCanvas) {


					var evt_pageX = evt.pageX || evt.touches[0].pageX;
					var evt_pageY = evt.pageY || evt.touches[0].pageY;

					$(".canvas-container").css({
						left: container_pos.x / window.scaleX + (evt_pageX - start_pos.x),
						top: container_pos.y / window.scaleY + (evt_pageY - start_pos.y),
						transform: "none"
					});

				}
			}).bind(PageEventType.startEvent, function (evt) {

				console.log(evt, "===========mousedown.evt=============");

				moveCanvas = true;

				var evt_pageX = evt.pageX || evt.touches[0].pageX;
				var evt_pageY = evt.pageY || evt.touches[0].pageY;

				start_pos = {
					x: evt_pageX,
					y: evt_pageY
				}

				container_pos = {
					x: $(".canvas-container").position().left,
					y: $(".canvas-container").position().top
				}


			}).bind(PageEventType.endEvent, function (evt) {
				moveCanvas = false;
				$('.canvas_mask').remove();
			}).bind(PageEventType.cancelEvent, function (evt) {
				moveCanvas = false;
				$('.canvas_mask').remove();
			});

			$(window).on(PageEventType.endEvent, function (e) {
				moveCanvas = false;
				$('.canvas_mask').remove();
			})


			that.setState({
				side_show: false
			})




		});

		// document.querySelector(".canvas_can_drag").click();

		$('.ShowPage_Main')[0].addEventListener('mousewheel', function (e) {
			var direction = e.deltaY > 0 ? 'down' : 'up'
			var num = direction == "up" ? 0.1 : -0.1
			that.canvasZoom(num);
		})

		//默认单元格给10cm宽高
		that.canvasZoomDirect(tenCmNeedZoom)

	}


	//左侧显示与隐藏切换
	handleToggleSideClick = () => {
		this.setState({
			side_show: !this.state.side_show
		})
	}


	//通过样式取宽高
	getDomRealData = (selector) => {
		var param = {
			css_width: parseFloat($(selector).css('width').replace('px', '')),
			css_height: parseFloat($(selector).css('height').replace('px', ''))
		};
		return param;
	}

	componentDidUpdate() {
		console.log(this.props.showStore.SetCurrentWordItem, "SetCurrentWordItem")
		console.log(this.props.showStore.currentWordImgList, "currentWordImgList")

		//重新画
	}

	//绽放
	canvasZoom(num) {
		var zoom = this._canvas.getZoom();
		zoom += num;
		message.config({
			top: 100,
			duration: 1,
			maxCount: 1,
		});
		if (zoom > 2 || zoom < 0.5) {
			message.warning('超出最大或最小缩比例！');
			return;
		}
		this.canvasZoomDirect(zoom);

	}

	//直接缩放至
	canvasZoomDirect(zoom) {
		this._canvas.setWidth(this.state.canvas_orign.width * zoom);
		this._canvas.setHeight(this.state.canvas_orign.height * zoom);
		this._canvas.setZoom(zoom);
		this.setCanvaWrapPosition();
	}

	//居中
	setCanvaWrapPosition() {

		var data = this.getDomRealData('.ShowPage_Main');

		$(this._canvas.wrapperEl).css({
			top: data.css_height / 2 + 'px',
			left: data.css_width / 2 + 'px',
			transform: "translate(-50%,-50%)"
		})
	}

	//放大
	canvasZoomIn = () => {
		this.canvasZoom(0.05)
	}

	//缩小
	canvasZoomOut = () => {
		this.canvasZoom(-0.05)
	}

	//清空画布
	canvasClear = () => {
		this._canvas.clear();
	}

	//切换画布背景
	canvasChangeBg = () => {
		var curBgImgIndex = this.state.bgImgActivedIndex;
		if (curBgImgIndex < this.state.bgImgList.length - 1) {
			this.setState({
				bgImgActivedIndex: curBgImgIndex + 1
			})
			curBgImgIndex = curBgImgIndex + 1;
		} else {
			this.setState({
				bgImgActivedIndex: 0
			})
			curBgImgIndex = 0
		}

		var curBgImgObj = this.state.bgImgList[curBgImgIndex];
		$(this._canvas.wrapperEl).css({
			backgroundImage: `url(${curBgImgObj.ImgUrl})`
		});
	}

	//左侧单击
	singleContainClick = (item) => {
		var that = this;
		console.log(item);

		this.props.showStore.SetCurrentWordItem(item);
		this.props.showStore.GetSingleWordListById(item.DirectoryID);

		//展示模板
		if (this.state.canvasMyMod == 0) {
			this.canvasClear();
			var that = this;

			var imgArr = [];
			imgArr = that.props.showStore.currentWordImgList.map(item => {
				item.ImageURL = item.ImageURL.indexOf('http') > -1 ? item.ImageURL : this.props.baseStore.picPreUrl + item.ImageURL;
				return item;
			})

			that.renderImgArr(imgArr, that._canvas);
			that._canvas.discardActiveObject();

		}
	}

	//显示视频
	showVideo = (e, item) => {
		e.stopPropagation();

		if (item.indexOf('http') == -1) {
			item = this.props.baseStore.picPreUrl + item;
		}

		this.setState({
			show_video: true,
			show_video_url: item
		})
	}

	//关闭视频
	closeVideo = () => {
		this.setState({ show_video: false })
	}

	toggleFreeDialog = () => {

		this.setState({ show_free_dialog: !this.state.show_free_dialog })
	}


	//画布拖动
	moveCanvasHandler = (type) => {

		//居中
		if (type == 0) {
			this.setCanvaWrapPosition();
			return;
		}

		var changTop = 0;
		var changLeft = 0;
		if (type == 1) {
			changTop = -10;
		} else if (type == 2) {
			changLeft = 10;
		} else if (type == 3) {
			changTop = 10;
		} else if (type == 4) {
			changLeft = -10;
		}

		var top = parseFloat($(".canvas-container").css('top').replace('px'))
		var left = parseFloat($(".canvas-container").css('left').replace('px'))
		console.log(top, "===========top=======");
		console.log(left, "===========left=======");



		$(".canvas-container").css({
			left: left + changLeft,
			top: top + changTop,
			transform: "translate(-50%,-50%)"
			// transform: "none"
		});
	}

	hideDialog = () => {
		this.setState({
			show_free_dialog: false
		})
	}

	changeFreeBg = (item) => {
		this.setState({
			freeBgUrl: item.ImgUrl
		})
	}

	render() {

		let sideClassName = "ShowPage_Side ";

		if (this.state.side_show) {
			sideClassName += " toggle_show";
		}

		if (!this.state.side_show) {
			sideClassName += " toggle_hide";
		}


		var sideMainCls = "ShowPage_Side_Main"
		if (this.props.showStore.rightList.length > 5) {
			sideMainCls += " has_scroll_bar";
		}


		var freeBgUrl = this.state.freeBgUrl;
		const styles = {
			freeBg: {
				backgroundImage: `url(${freeBgUrl})`
			}
		}




		return (

			<div className="ShowPage page_container  fadeInDown fast" >


				<div className={sideClassName} ref="_side" >


					<div className={sideMainCls} ref="_tool" >
						{
							this.props.showStore.rightList.map((item, index) => {
								return (
									<div className="single_container" key={index} onClick={() => this.singleContainClick(item)}>
										<div className="single_img_container">
											<img src={this.props.baseStore.picPreUrl + '/' + item.ImageURL} alt="" />
										</div>
										<div className="single_bottom_container">


											<div key={index} onClick={(e) => this.showVideo(e, item.VideoURL)}>
												<img src={ImageLoader.video_white} alt="" />
											</div>

											<div key={index} onClick={(e) => this.showVideo(e, item.AnimationURL)}>
												<img src={ImageLoader.video_white} alt="" />
											</div>



										</div>

									</div>
								)
							})
						}


					</div>


					<div className="ShowPage_Tool" ref="_tool" >

						<div className="" onClick={this.toggleFreeDialog}>
							自由临摹
						</div>
						<div className="canvas_can_drag">
							整体拖动
						</div>
						<div className="canvas_zoom_out" onClick={() => this.canvasZoomDirect(1)}>
							初始比例
						</div>
						<div className="canvas_zoom_in" onClick={this.canvasZoomIn}>
							比例放大
						</div>
						<div className="canvas_zoom_out" onClick={this.canvasZoomOut}>
							比例缩小
						</div>
						<div className="canvas_clear" onClick={this.canvasClear}>
							清除画布
						</div>
						<div className="canvas_toggle_bg" onClick={this.canvasChangeBg}>
							切换背景
						</div>
						<div className="canvas_can_drag" onClick={() => this.moveCanvasHandler(0)}>
							居中移动
						</div>
						<div className="canvas_can_drag" onClick={() => this.moveCanvasHandler(1)}>
							向上移动
						</div>
						<div className="canvas_can_drag" onClick={() => this.moveCanvasHandler(3)}>
							向下移动
						</div>
						<div className="canvas_can_drag" onClick={() => this.moveCanvasHandler(2)}>
							向左移动
						</div>
						<div className="canvas_can_drag" onClick={() => this.moveCanvasHandler(4)}>
							向右移动
						</div>

					</div>

					<div onClick={this.handleToggleSideClick} className="ShowPage_Tool_Min fixed" ref="_tool_min" >
						<Icon type={this.state.side_show ? "arrow-left" : "arrow-right"} />
					</div>


				</div>



				<div className="ShowPage_Main" >


					<div>
						{this.props.showStore.currentShowTemplate}
					</div>

					<canvas id="canvas" ></canvas>

					{/* <input type="text" /> */}


				</div>
				{
					// this.state.show_img && (<div className="wrap_for_show_create_img" onClick={this.hideShowImg} >
					// 	<img download className="img_for_show_create_img" src={this.state.show_img_url} alt="" />
					// 	<Button />
					// </div>)


					this.state.show_video && (<Modal
						title="视频播放"
						centered={true}
						width={1020}
						height={600}
						cancelText="关闭"
						okText="下载(注：因为白色字,打开可能看不出效果哦)"
						visible={this.state.show_video}
						footer={null}
						onCancel={this.closeVideo}
						wrapClassName="show_video_wrap"
					>
						<video width="1000px" height="600px" autoPlay className="my_video" src={this.state.show_video_url} controls="controls">
						</video>

					</Modal>)
				}

				{
					this.state.show_free_dialog ? (

						<div className="show_free_dialog ">
							<div className="free_side">
								<div className="free_side_each"></div>
								<div className="free_side_each"></div>
								<div className="free_side_each"></div>
								<div className="free_side_each"></div>
								<div className="free_side_each"></div>
							</div>
							<div className="free_right">
								<div className="free_right_01">
									<img src={ImageLoader.free_title} alt="" />
								</div>
								<div className="free_right_02">
									{
										this.state.bgImgList.map(item => {
											return (

												<div onClick={() => { this.changeFreeBg(item) }}>
													<img src={ImageLoader[item.Icon]} alt="" />
													{item.Name}
												</div>
											)
										})
									}
								</div>
								<div className="free_right_03" style={styles.freeBg} >

									<img className="free_each" src={this.props.baseStore.picPreUrl + 'Images/wordpic/二-单字.png'} />
									<img className="free_each" />
									<img className="free_each" />
									<img className="free_each" />
									<img className="free_each" />
									<img className="free_each" />
									<img className="free_each" />
									<img className="free_each" />

								</div>
								<div className="free_right_04"></div>
							</div>
						</div>
					) : null
				}


				{
					this.state.show_free_dialog ? (
						<div className="ant-modal-mask" onClick={this.hideDialog}>

						</div>
					) : null
				}







			</div >
		);


	}
}

export default ShowPage;